package com.learn.retry;

import org.springframework.retry.RetryCallback;
import org.springframework.retry.RetryContext;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;

/**
 * @author Created by chenxin34 on 2018/12/22 下午12:11.
 */
public class RetryTest {
    public static void main(String[] args) {
        RetryTemplate retryTemplate = new RetryTemplate();
        try {

            retryTemplate.execute(new RetryCallback<Object, Exception>() {
                @Override
                public Object doWithRetry(RetryContext retryContext) throws Exception {
                    if (retryContext.getLastThrowable() != null) {
                        System.out.println("retry times = " + retryContext.getRetryCount() + "e = " + retryContext.getLastThrowable());
                    }
                    throw new RuntimeException("run ex");
//                    return null;
                }
            });
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public static RetryTemplate newRetryTemplate() {
        RetryTemplate retryTemplate = new RetryTemplate();
        SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
        simpleRetryPolicy.setMaxAttempts(3);
        retryTemplate.setRetryPolicy(simpleRetryPolicy);
        retryTemplate.setBackOffPolicy(new ExponentialBackOffPolicy());
        return retryTemplate;
    }
}
